package com.ibix.daoImpl;

import com.ibix.dao.BaseDao;
import com.ibix.dao.UserDao;
import com.ibix.entity.Users;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

// 实现类
public class UserDaoImpl extends BaseDao implements UserDao {

    Connection connection;
    PreparedStatement preparedStatement;
    ResultSet resultSet;

    public int addUser(Users u) {
        int num = 0;
        String sql = "insert into users(name,age) values(?,?)";
        try {
            num = updateUser(sql, u.getName(), u.getAge());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return num;
    }

    public int delUser(int id) {
        int num = 0;
        String sql = "delete from users where id=?";
        try {
            num = updateUser(sql, id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return num;
    }

    public int updateUser(Users u) {
        int num = 0;
        String sql = "update users set name=?,age=? where id=?";
        try {
            num = updateUser(sql, u.getName(), u.getAge(), u.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return num;
    }

    public Users findUserById(int id) {
        Users u = null;
        String sql = "select * from users where id=?";
        resultSet = executeQuery(sql, id);
        try {
            if (resultSet.next()) {
                u = new Users(resultSet.getInt(1), resultSet.getString(2), resultSet.getInt(3));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return u;
    }

    public List<Users> getAllUsers() {
        List<Users> ulist = new ArrayList<Users>();
        String sql = "select * from users";

        /* BaseDao 里面的方法 查询语句 */
        resultSet = executeQuery(sql);
        try {
            while (resultSet.next()) {
                Users u = new Users(resultSet.getInt(1), resultSet.getString(2), resultSet.getInt(3));
                ulist.add(u);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ulist;
    }
}
